package cn.tedu.v3;

import java.io.*;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 *  Version3.0 升级  双向链接【客户端与服务器相互说话】
 *
 *  优化空间：代码结构、流没有关闭
 */
public class Server {
    private ServerSocket serverSocket;
    public Server(){
        try {
            serverSocket=new ServerSocket(6666);
        } catch(BindException e) {
            System.out.println("端口号重复创建....");
        }catch (IOException e) {
            System.out.println("申请端口号失败");
        }
    }

    public void start(){
        try {
            while(true){
                        System.out.println("----等待客户端连接----");
                        Socket socket = serverSocket.accept();
                        String ip = socket.getInetAddress().getHostAddress();
                        System.out.println(ip + "一个客户端链接成功了");

                    //优化代码行数：CS多线程类：处理多个客户端
                    new Thread(new CS(socket)).start();
                    }
        } catch (IOException e) {
            System.out.println("服务器端通讯断开了");
        }finally { //一定会被执行代码段，关闭服务器端通讯类
            //判断条件：判断服务器端通讯是否为空并且判断对象后是否未关闭
            if(serverSocket!=null&&serverSocket.isClosed()){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    System.out.println("服务器关闭失败");
                }
            }
            // 找 Server类中： CS多线程类--run方法--关闭socket
        }
    }

    public static void main(String[] args) throws IOException {
        Server server=new Server();
        server.start();
    }

    private class CS implements Runnable{
        private Socket socket;
        private String ip;

        public CS(Socket s){
            this.socket=s;

            ip=socket.getInetAddress().getHostAddress();
        }

        public void run() {
            BufferedReader br=null;
            try {
            //1.读入定义
              br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8"));
            //2.定义写出
          PrintWriter pw=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF8")),true);

          //1.1读入功能：存线程中

                BufferedReader finalBr = br;
                new Thread(()->{
                    try {
                        String message;
                        while((message= finalBr.readLine())!=null){
                            System.out.println("客户端说："+message);
                            //增加写出一句话：读完卡住等待输入
                            System.out.println("服务器端请输入：");
                        }
                    } catch (IOException e) {
                        System.out.println("客户端读入失败！");
                    }
                }).start();
                //2.1 提供写方法：控制台输入
            Scanner input =new Scanner(System.in);//后台卡住
            while (true) {
                System.out.println("服务器端请输入：");
                String say= input.nextLine();//得到控制台输入值
                //打印服务器端说的文本---打印客户端
                pw.println("服务器说："+say);
            }
            } catch(NullPointerException e){
                System.out.println("IO流传输对象，" +
                        "有对象为null，立马核对，" +
                        "建议：查看try块中的对象赋值为null");
            } catch (UnsupportedEncodingException e) {
                System.out.println("客户端或者服务器端：字符集不一致");
            } catch (IOException e) {
                System.out.println("通讯过程当中，传输出现错误！");
            } finally {
                if(br!=null)
                    try {
                        br.close();
                    } catch (IOException e) {
                        System.out.println("结束通讯：关闭失败！");
                    }
                if(socket!=null&&!socket.isClosed())
                    try {
                        socket.close();
                    } catch (IOException e) {
                        System.out.println("通讯关闭失败~");
                    }
            }
        }
    }

}